package com.topcent.tioxyc.xxljob;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.Customer;
import com.topcent.tioxyc.pojo.vo.C2425DjVO;
import com.topcent.tioxyc.pojo.vo.C2526DjVO;
import com.topcent.tioxyc.pojo.vo.CustomerDjVO;
import com.topcent.tioxyc.pojo.vo.CustomerInfoVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: weidian
 * @date: 2024/11/27 11:24
 * @Description: 跟新简道云的等级划分字段
 */
@Slf4j
@Component
public class CustomerInfoXxlJob {
    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    //@XxlJob("CustomerInfoXxlJob")2025-09-16弃用
    public void customerInfoXxlJob() {
        List<CustomerInfoVO> customerInfoWithSAP = yy1KpiMapper.getCustomerInfoWithSAP();
        for (CustomerInfoVO customerInfoVO : customerInfoWithSAP) {
            Header[] headers = ConnmeUtils.createHeaders();
            Map<String, Object> parameterCxv = new HashMap<>();
            parameterCxv.put("app_id", "66a6f42ff97af74b02d217df");
            parameterCxv.put("entry_id", "66a6f443333584e2c128154f");
            HashMap<String, String> communti = new HashMap<>();
            communti.put("_widget_1728356780097", customerInfoVO.getSapCode());
            List<Customer> customers = PurchaseCommunity.queryBased(parameterCxv, headers, communti, Customer.class);
            if (!customers.isEmpty()) {
                // 获取字段值，并安全处理可能的空指针
                String amount23 = customerInfoVO.getCustomerAmount_23() != null
                        ? ConnmeUtils.formatToWan(customerInfoVO.getCustomerAmount_23())
                        : null;
                String level23 = customerInfoVO.getCustomerLevel_23();

                String amount24 = customerInfoVO.getCustomerAmount_24() != null
                        ? ConnmeUtils.formatToWan(customerInfoVO.getCustomerAmount_24())
                        : null;
                String level24 = customerInfoVO.getCustomerLevel_24();

                String amount25 = customerInfoVO.getCustomerAmount_25() != null
                        ? ConnmeUtils.formatToWan(customerInfoVO.getCustomerAmount_25())
                        : null;
                String level25 = customerInfoVO.getCustomerLevel_25();
                String combination23 = (amount23 != null ? amount23 : "-") + "-" + (level23 != null ? level23 : "-");
                String combination24 = (amount24 != null ? amount24 : "-") + "-" + (level24 != null ? level24 : "-");
                String combination25 = (amount25 != null ? amount25 : "-") + "-" + (level25 != null ? level25 : "-");
                String dengji = combination23 + ", " + combination24 + ", " + combination25;

                customers.getFirst().set_widget_1727682254107(dengji);
                // 1. 先用Long接收（允许null）
                Long amount2526Obj = customerInfoVO.getCustomerAmount_25();
                // 2. 判断是否为null，为空则用"0"，否则转字符串
                String amountStr = amount2526Obj == null ? "0" : String.valueOf(amount2526Obj);
                // 3. 赋值
                customers.getFirst().set_widget_1756345467424(amountStr);

                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "66a6f42ff97af74b02d217df");
                parameterInster.put("entry_id", "66a6f443333584e2c128154f");
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("data_id", customers.getFirst().get_id());
                customers.getFirst().set_id(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(customers.getFirst()));
                String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
            }
        }
    }

    @XxlJob("customerDjXxlJob")
    public String customerDjXxlJob() {
        // 获取客户主数据的全量等级客户数据
        List<CustomerDjVO> customerDjVOList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a6f42ff97af74b02d217df");
        parameter.put("entry_id", "66a6f443333584e2c128154f");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<CustomerDjVO> list = JSONUtil.toList(objects, CustomerDjVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            customerDjVOList.addAll(list);
        } while (fale);

        // 获取2425年全量等级客户数据
        List<C2425DjVO> c2425Dj = getC2425Dj(headers);
        Map<String, String> c2425LevelMap = c2425Dj.stream()
                .collect(Collectors.toMap(
                        C2425DjVO::get_widget_1753669549571,  // 键：客户编码
                        C2425DjVO::get_widget_1753669549574,  // 值：2425财年客户等级
                        (existing, replacement) -> existing   // 若有重复客户编码，保留第一个
                ));

        //  获取2526财年数据（金额聚合+等级计算）- 原有逻辑不变
        Map<String, Long> c2526AmountMap = getC2526DjAggregated(headers); // 客户编码→累计金额（Long）
        Map<String, String> c2526LevelMap = c2526AmountMap.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> {
                            BigDecimal salesAmount = new BigDecimal(entry.getValue());
                            if (salesAmount.compareTo(new BigDecimal("10000000")) >= 0) return "GSKA";
                            else if (salesAmount.compareTo(new BigDecimal("3000000")) >= 0) return "SKA";
                            else if (salesAmount.compareTo(new BigDecimal("1000000")) >= 0) return "KA";
                            else if (salesAmount.compareTo(new BigDecimal("300000")) >= 0) return "PA";
                            else return "AA";
                        }
                ));

        // 核心逻辑：遍历客户主数据，匹配并填充2425/2526的等级和销售额
        for (CustomerDjVO customerDjVO : customerDjVOList) {
            // 4.1 获取当前客户的编码（从CustomerDjVO中取）
            String currentCustCode = customerDjVO.get_widget_1722305048887();
            // 跳过客户编码为空的无效数据
            if (currentCustCode == null || currentCustCode.trim().isEmpty()) {
                continue;
            }

            // 匹配2425财年等级（有则取，无则空）
            String c2425Level = c2425LevelMap.getOrDefault(currentCustCode, "");

            // 匹配2526财年数据（金额+等级）
            Long c2526Amount = c2526AmountMap.get(currentCustCode); // 2526累计金额（Long，可能为null）
            String c2526Level = c2526LevelMap.getOrDefault(currentCustCode, ""); // 2526等级（可能为空）

            // 拼接客户等级：按规则组合2425和2526的等级（示例："2425等级-2526等级"，可按需调整）
            String finalLevel = c2425Level + "-" + c2526Level;

            // 填充2526累计销售额（用工具类转为"万"单位）
            String formatted2526Amount = "";
            if (c2526Amount != null) {
                formatted2526Amount = String.valueOf(c2526Amount); // 调用工具类转换格式
            }

            // 赋值到CustomerDjVO中
            customerDjVO.set_widget_1727682254107(finalLevel); // 填充客户等级（FY2425-FY2526）
            customerDjVO.set_widget_1756345467424(formatted2526Amount); // 填充2526累计销售额

            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", "66a6f42ff97af74b02d217df");
            parameterInster.put("entry_id", "66a6f443333584e2c128154f");
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", customerDjVO.get_id());
            customerDjVO.set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(customerDjVO));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
        }
        return "执行完成，处理客户数量：" + customerDjVOList.size();
    }

    // 获取2425年全量等级客户数据
    public List<C2425DjVO> getC2425Dj(Header[] headers) {
        List<C2425DjVO> c2425DjVOList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "67f8aa2676b9b3942c49035f");
        parameter.put("entry_id", "6886dfadc0295dd7a573b661");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<C2425DjVO> list = JSONUtil.toList(objects, C2425DjVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            c2425DjVOList.addAll(list);
        } while (fale);
        return c2425DjVOList;
    }

    // 获取2526年全量等级客户数据，并按客户编号聚合累计金额
    public Map<String, Long> getC2526DjAggregated(Header[] headers) {
        // 1. 获取原始数据列表
        List<C2526DjVO> c2526DjVOList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "67f8aa2676b9b3942c49035f");
        parameter.put("entry_id", "67f8aa6d945a5abcaab9369e");
        boolean hasMore = true;
        String lastDataId = "";

        // 添加时间范围过滤条件
        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "_widget_1743998205163");
        cond.put("type", "datetime");
        cond.put("method", "range");
        List<String> values = new ArrayList<>();
        values.add("2025-07-01");
        values.add("2026-06-30");
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        // 分页获取所有数据
        do {
            if (!lastDataId.isEmpty()) {
                parameter.put("data_id", lastDataId);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<C2526DjVO> list = JSONUtil.toList(objects, C2526DjVO.class);

            if (list.size() == 100) {
                lastDataId = list.getLast().get_id();
            } else {
                hasMore = false;
            }
            c2526DjVOList.addAll(list);
        } while (hasMore);

        // 2. 直接按客户编号分组，累加金额（使用Stream流简化实现）
        return c2526DjVOList.stream()
                .collect(Collectors.groupingBy(
                        // 分组键：客户编号
                        C2526DjVO::get_widget_1743997558329,
                        // 累加器：汇总金额，处理null为0
                        Collectors.summingLong(vo -> vo.get_widget_1743997558339() == null ? 0L : vo.get_widget_1743997558339())
                ));
    }
}
